<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/13 0013
 * Time: 15:22
 */

namespace app\admin\controller;


use app\admin\model\Member;
use think\Db;
use think\Request;
use OSS\OssClient;
use OSS\Core\OssException;

class Activity extends Base
{

    public function __construct()
    {
        $request = Request::instance();
        parent::__construct($request);
        //判断活动结束没。。
        $curr_time=time();
        $list=db('activity')->where('status',1)->where('end_time','<',$curr_time)->order('id desc')->select();
        foreach ($list as $v)
        {
            $data=[];
            $data['status']=2;
            db('activity')->where('id',$v['id'])->update($data);
        }
    }

    public function lists()
    {
        if (isset($this->_param['op']) && $this->_param['op'] == 'table') {

            if(isset($this->_param['status'])&&$this->_param['status']==10)
            {
                unset($this->_map['status']);
            }
            if(isset($this->_param['start_time'])&&$this->_param['start_time']!='')
            {
                $this->_btw = strtotime($this->_param['start_time']);
                $this->_map['start_time'] = ['>', $this->_btw];
            }
            if(isset($this->_param['end_time'])&&$this->_param['end_time']!='')
            {
                $this->_btw = strtotime($this->_param['end_time']);
                $this->_map['end_time'] = ['<', $this->_btw];
            }

            $list = db('activity')->order('id desc');
            $total = $list->count();
            $list->limit(($this->_param['page'] - 1) * $this->_param['limit'], $this->_param['limit']);
            $where = $this->_map;
            unset($where['page']);
            unset($where['op']);
            unset($where['limit']);
            (!empty($where)) ? $data = $list->where($where)->order('id desc')->select() : $data = $list->order('id desc')->select();
            $this->assign('map', $this->_param);
            foreach ($data as $k => $v) {
                $flag[-1]='<span class="layui-badge layui-bg-gray">未设置</span>';
                $flag[0]='<span class="layui-badge layui-bg-red">'.$v['btn_0'].'</span>';
                $flag[1]='<span class="layui-badge layui-bg-green">'.$v['btn_1'].'</span>';
                $data[$k]['start_time'] = $data[$k]['start_time'] ? date('Y-m-d H:i:s', $v['start_time']) : '';
                $data[$k]['end_time'] = $data[$k]['end_time'] ? date('Y-m-d H:i:s', $v['end_time']) : '';
                $data[$k]['result']=$flag[$data[$k]['result_flag']];
            }
            $this->ajaxReturn('', $data, $total);
        }
        if (!isset($this->_param['op'])) {
            return $this->fetch('lists');
        }
    }

    //添加活动
    public function add_act()
    {
        return $this->fetch('add_act');
    }

    //添加类别操作
    public function adding_act()
    {
        $this->_param['status']=-1;
        $this->_param['create_time']=time();
        $this->_param['start_time']=strtotime($this->_param['start_time']);
        $this->_param['end_time']=strtotime($this->_param['end_time']);

        $temp = Db::name('activity')->insert($this->_param);
        if ($temp) {
            $this->success('添加成功!');
        } else {
            $this->success('添加失败!');
        }
    }

    //编辑活动
    public function edit($id)
    {
        $url = $this->url;
        $act = \db('activity')->where('id', $id)->find();
        $act['t_img'] = $act['img'];
        $act['img'] = $url . '/uploads/activity/' . $act['img'];
        $act['start_time'] = date('Y-m-d H:i:s', $act['start_time']);
        $act['end_time'] = date('Y-m-d H:i:s', $act['end_time']);

        $this->assign('act', $act);
        return $this->fetch('add_act');
    }

    public function editing()
    {
        $this->_param['start_time']=strtotime($this->_param['start_time']);
        $this->_param['end_time']=strtotime($this->_param['end_time']);
        $temp = Db::name('activity')->update($this->_param);
        if ($temp) {
            $this->success('编辑成功!');
        } else {
            $this->success('编辑失败!');
        }
    }

    //上架活动
    public function up_act($id)
    {
        $data['status']=1;
        Db::name('activity')->where('id',$id)->update($data);
        $this->ajaxReturn("操作成功", 200);
    }

    //设置答案
    public function set_result($id)
    {
        $list=db('cate_card')->select();
        $this->assign('act',$list);
        return $this->fetch('set_result');
    }

    //设置答案
    public function set_flag($id,$flag)
    {
        $data['status']=3;
        $data['result_flag']=$flag;
        Db::name('activity')->where('id',$id)->update($data);
        $this->ajaxReturn("操作成功", 200);
    }

    //开始清算
    public function start_clear($id)
    {
        $act=db('activity')->where('id',$id)->where('status',3)->find();
        if(empty($act)) $this->ajaxReturn("活动不存在", 201);
        if($act['cash_pool']==0){ //活动结束
            $data = [];
            $data['status']=0;
            Db::name('activity')->where('id',$id)->update($data);
            $this->ajaxReturn("清算完毕", 200);
        }
        //计算获胜的LCC投入数量
        $sl_count=db('activity_user')->where('act_id',$id)->where('select_flag',$act['result_flag'])->sum('put_lcc');
        $count=$act['cash_pool']/0.8/$sl_count;//每份的LCC数量

        $list=db('activity_user')->where('act_id',$id)->where('select_flag',$act['result_flag'])->select();
        Db::startTrans();
        try {
            foreach ($list as $v) {
                $reward_lcc = round($count * $v['put_lcc'] * 0.8,2); //用户应得的份数
                //修改记录
                $data = [];
                $data['reward_lcc'] = $reward_lcc;
                db('activity_user')->where('id', $v['id'])->update($data);

                //增加用户 LCC币
                $user = \app\admin\model\Member::get(['id' => $v['uid']]);
                $reward = $data['reward_lcc'];
                $data = [];
                $data['lcc_wallet'] = $user['lcc_wallet'] + $reward;
                Db::name('member')->where('id',$v['uid'])->update($data);

                //活动结束
                $data = [];
                $data['status']=0;
                Db::name('activity')->where('id',$id)->update($data);

                //添加流水
                add_bill($v['uid'], $reward_lcc, 2, 13);
            }
            Db::commit();
        }
        catch (\Exception $e) {
            Db::rollback();
            $this->ajaxReturn("清算失败", 201,0,1);
        }
        $this->ajaxReturn("清算成功", 200);
    }

    //删除订单
    public function del_act()
    {
        $act = db('activity')->where('status=-1')->where('id', $this->_param['id'])->find();
        if (empty($act)) $this->ajaxReturn("订单状态不存在", 201);
        Db::name('activity')->delete($act);
        $this->ajaxReturn("删除成功", 200);
    }

    //获取用户
    public function user_list()
    {
        if (isset($this->_param['op']) && $this->_param['op'] == 'table') {
            $list = db('activity_user')->where('act_id',$this->_param['act_id'])->order('id desc');
            $act=db('activity')->where('id',$this->_param['act_id'])->find();
            $flag[0]='<span class="layui-badge layui-bg-red">'.$act['btn_0'].'</span>';
            $flag[1]='<span class="layui-badge layui-bg-cyan">'.$act['btn_1'].'</span>';
            $total = $list->count();
            $list->limit(($this->_param['page'] - 1) * $this->_param['limit'], $this->_param['limit']);
            $where = $this->_param;
            unset($where['page']);
            unset($where['op']);
            unset($where['limit']);
            (!empty($where)) ? $data = $list->where($where)->order('id desc')->select() : $data = $list->order('id desc')->select();
            $this->assign('map', $this->_param);
            foreach ($data as $k => $v) {
                $user=Member::get(['id'=>$v['uid']]);
                $data[$k]['create_time'] = $data[$k]['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '';
                $data[$k]['nickname']=$user['nickname'];
                $data[$k]['select_flag']= $flag[$data[$k]['select_flag']];
            }
            $this->ajaxReturn('', $data, $total);
        }
        if (!isset($this->_param['op'])) {
            $this->assign('act_id', $this->_param['act_id']);
            return $this->fetch('user_list');
        }


    }

    function upload()
    {
        $path = '/uploads/activity/';
        $new_dir = isset($new_dir) ? $new_dir : $_SERVER['DOCUMENT_ROOT'] . $path;
        if (!file_exists($new_dir)) {
            $this->createDir($new_dir);
        }
        foreach ($_FILES as $name => $file) {
            $file_types = explode(".", $file['name']);
            $file_type = $file_types [count($file_types) - 1];
            $fn = substr(md5(rand(1, time())), rand(0, 8), 20) . '.' . $file_type;
            $ft = strrpos($fn, '.', 0);
            $fm = substr($fn, 0, $ft);
            $fe = substr($fn, $ft);
            $fp = $_SERVER['DOCUMENT_ROOT'] . $path . $fn;
            $fi = 1;

            if (!in_array(strtolower($file_type), array('gif', 'png', 'jpg', 'jpeg'))) {
                $this->ajaxReturn('格式不对', 201);
            }

            while (file_exists($fp)) {
                $fn = $fm . '[' . $fi . ']' . $fe;
                $fp = $_SERVER['DOCUMENT_ROOT'] . $path . $fn;;
                $fi++;
            }

            $result = move_uploaded_file($file['tmp_name'], $fp);
        }

        if ($result) {

            //上传阿里云OSS
            if(true)
            {
                $root = $_SERVER['DOCUMENT_ROOT'];
                if (is_file($root . '/../extend/oss/autoload.php')) {
                    require_once $root . '/../extend/oss/autoload.php';
                }
                $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
                try {
                    $ossClient->uploadFile($this->bucket, substr($path,1).$fn, $fp);
                    unlink($fp);
                } catch (OssException $e) {
                    printf($e->getMessage() . "\n");
                    return;
                }
            }

            $this->ajaxReturn('修改成功', 200, $fn);
        } else {
            // 上传失败返回错误信息
            $this->ajaxReturn('图片上传失败', 201);
        }
    }

}